<template>
  <view class="list">
    <u-cell-group :border="false">
      <u-cell
        title="关联单号"
        @click="
          () => goToPath('/pages/orderList/receipt/receiptList?isSelect=true')
        "
        :clickable="true"
        :border="false"
        ><template #value>
          <view class="flex">
            <text class="value" :class="!contactOrder.orderCode && 'noValue'">{{
              contactOrder.orderCode || "请选择收货单"
            }}</text>
            <u-icon name="arrow-down-fill" size="10"></u-icon>
          </view>
        </template>
      </u-cell>
      <u-cell
        title="退货日期"
        @click="() => goToPath('/pages/order/delyveryDate')"
        :border="false"
        :clickable="true"
      >
        <template #value>
          <view class="flex">
            <text class="text">{{ deliveryDateTime }}</text>
            <u-icon name="arrow-down-fill" size="10"></u-icon>
          </view>
        </template>
      </u-cell>
      <u-cell
        title="退货类型"
        @click="show = true"
        :border="false"
        :clickable="true"
      >
        <template #value>
          <view class="flex">
            <text class="value">{{ formData.type.name }}</text>
            <u-icon name="arrow-down-fill" size="10"></u-icon>
          </view>
        </template>
      </u-cell>
    </u-cell-group>
  </view>

  <view class="list">
    <u-cell-group :border="false">
      <u-cell :border="false" title="备注">
        <template #value>
          <view style="flex: 6">
            <up-input
              inputAlign="right"
              v-model="formData.remark"
              placeholder="请输入备注信息"
              border="none"
            ></up-input>
          </view>
        </template>
      </u-cell>
    </u-cell-group>
  </view>
  <view class="list">
    <u-cell-group :border="false">
      <u-cell :border="false" title="附件">
        <template #label>
          <view style="margin-top: 10px">
            <u-upload
              width="36"
              height="36"
              :fileList="fileList"
              @afterRead="afterRead"
              @delete="deleteFn"
              uploadIcon="plus"
              name="image"
              :maxCount="Max_FILE"
            ></u-upload>
          </view>
        </template>
      </u-cell>
    </u-cell-group>
  </view>
  <view class="addBtn">
    <u-button
      type="primary"
      :plain="true"
      shape="circle"
      size="mini"
      @click="goToGoods"
      text="增加商品"
    ></u-button>
  </view>
  <godsList :infoList="infoList" @del="handleDel" @edit="handleEdit"></godsList>
  <u-action-sheet
    round="20"
    @close="show = false"
    @select="(item) => (formData.type = item)"
    :closeOnClickOverlay="true"
    :actions="typeList"
    :show="show"
  ></u-action-sheet>
  <view class="bottom">
    <view class="left">
      <text class="sum"
        >共：<text>{{ total }}件</text></text
      >
      <text class="sum"
        >总计：<text>￥{{ totalPrice }}</text></text
      >
    </view>
    <view class="right">
      <u-button
        @click="handleClick"
        style="height: 100%"
        type="primary"
        size="mini"
        shape="circle"
        text="提交"
      ></u-button>
    </view>
  </view>
  <editOrder :options="options" ref="editRef" @submit="handleSubmit">
  </editOrder>
  <u-modal
    :show="modalShow"
    confirmColor="#FD4D00"
    @confirm="delSubmit"
    @cancel="closeWindows"
    :showCancelButton="true"
    title="提示"
    content="确定删除该商品吗?"
  ></u-modal>
</template>

<script setup>
import { ref, reactive, computed, onBeforeUnmount } from "vue";
import godsList from "@/components/orderList/goodsList.vue";
import { onLoad } from "@dcloudio/uni-app";
import { message } from "@/hooks/useToast.js";
import {
  returnOrderAdd,
  returnOrderDetail,
  returnOrderEdit,
} from "@/api/order";
import editOrder from "@/components/commodity/editOrder.vue";
import { useOrderStore } from "@/store/order";
import { useUserStore } from "@/store/user";
import { useUploadFile, Max_FILE } from "@/hooks/useUpload";
const { fileList, afterRead, deleteFn, initData } = useUploadFile();
const orderStore = useOrderStore();
const userStore = useUserStore();
import { Type_Return } from "../config";

const show = ref(false);
const formData = reactive({
  type: {
    name: "",
    value: "",
  },
  remark: "",
});
const contactOrder = computed(() => {
  return orderStore.contactOrder || {};
});
const totalPrice = computed(() => {
  return uni.$u.priceFormat(orderStore.totalPrice, 2);
});
const total = computed(() => {
  return orderStore.total;
});
const shopList = computed(() => {
  return orderStore.goodsList;
});
const infoList = computed(() => {
  return Type_Return.detailInfoList();
});
const shopId = computed(() => {
  return userStore.shopId;
});
const typeList = ref([]);
const getTypeList = async () => {
  let arr = await Type_Return.type();
  formData.type = arr[0];
  typeList.value = arr;
  return arr;
};
// 编辑项
const options = computed(() => {
  return Type_Return.options();
});
const id = ref("");
onLoad((params) => {
  if (params.id) {
    id.value = params.id;
    getDetail();
  } else {
    getTypeList();
  }
});

const getDetail = async () => {
  const arr = await getTypeList();
  const res = await returnOrderDetail({
    id: id.value,
  });
  const respOmsReturnorderDTO = res.respOmsReturnorderDTO;
  formData.remark = respOmsReturnorderDTO.remark;
  arr.forEach((btn) => {
    if (btn.value === respOmsReturnorderDTO.returnReason) {
      formData.type = btn;
    }
  });
  // 关联单号
  orderStore.setContactOrder({
    orderCode: respOmsReturnorderDTO.returnorderCode,
  });
  //  附件
  if (res.espOmsReturnorderImageDTOList) {
    initData(
      res.espOmsReturnorderImageDTOList.map((btn) => {
        return {
          url: btn.returnorderImage,
        };
      })
    );
  }
  // 设置时间
  orderStore.setDataTime(respOmsReturnorderDTO.returnorderDate);
  // 商品
  orderStore.setShopList({
    data: res.respOmsReturnorderInfoDTOList.map((btn) => {
      btn.qty = btn.returnorderNum;
      btn.unitPrice = btn.returnorderPrice;
      return btn;
    }),
    type: "Return",
  });
};
// 送货日期
const deliveryDateTime = computed(() => {
  return orderStore.deliveryDateTime;
});
const goToPath = (path) => {
  uni.navigateTo({ url: path });
};

const editRef = ref();
const handleEdit = (data) => {
  editRef.value?.open(data.item);
};
const handleSubmit = async (data) => {
  const res = await orderStore.updateData(data);
  if (res) {
    editRef.value?.close();
  }
};
const modalShow = ref(false);
let _current = null;
const handleDel = (params) => {
  modalShow.value = true;
  _current = params;
};
const delSubmit = () => {
  orderStore.deleteShopListItem(_current);
  modalShow.value = false;
  message("删除成功");
  _current = null;
};
const closeWindows = () => {
  modalShow.value = false;
};
const goToGoods = () => {
  uni.navigateTo({
    url: "/pages/orderList/selectGoods?type=Return",
  });
};
onBeforeUnmount(() => {
  orderStore.clearData();
});
const handleClick = async () => {
  if (shopList.value.length === 0) {
    message("请添加商品");
    return;
  }
  let baseData = {
    // 附件
    requestOmsReturnorderImageDTOList: fileList.value.map((btn) => {
      return {
        returnorderImage: btn.url,
      };
    }),
    // 商品
    requestOmsReturnorderInfoDTOList: shopList.value.map((btn) => {
      btn.returnorderNum = btn.qty;
      btn.auxiliaryunitId = btn.unitId;
      btn.returnorderPrice = btn.unitPrice;
      return btn;
    }),
    requestOmsReturnorderDTO: {
      returnorderDate: orderStore.deliveryDateTimeStr,
      remark: formData.remark,
      shopId: shopId.value,
      returnorderCode: contactOrder.value.orderCode,
      returnReason: formData.type.value,
    },
  };
  console.log(formData.type);
  if (id.value) {
    baseData.requestOmsReturnorderDTO.id = id.value;
    // 编辑
    await returnOrderEdit(baseData);
  } else {
    await returnOrderAdd(baseData);
  }
  uni.navigateBack();
};
</script>

<style lang="scss">
page {
  background-color: #f9f9f9;
  padding-bottom: calc(67px + env(safe-area-inset-bottom));
}
.list {
  background-color: #fff;
  margin-top: 10px;

  .flex {
    display: flex;
    align-items: center;

    .text,
    .value {
      margin-right: 8px;
      &.noValue {
        color: #a0a0a0;
      }
    }
  }

  .text {
    color: #fd4d00;
  }
}
.addBtn {
  width: 69px;
  margin: 11px 13px 12px auto;
}
.bottom {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 57px;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: env(safe-area-inset-bottom);
  padding-right: 10px;
  padding-left: 19px;
  border-top: 1px solid #e5e5e5;
  z-index: 1000;

  .left {
    .sum {
      font-size: 14px;
      color: #7f7f7f;
      & + .sum {
        margin-left: 68px;
      }
    }
  }

  .right {
    width: 80px;
  }
}
</style>
